package com.geralt.im.controller;

import java.util.ArrayList;

import com.geralt.im.command.Command;
import com.geralt.im.commandenum.Code;
import com.geralt.im.jsonparser.IjsonParser;
import com.geralt.im.parse.impl.RqParser;
import com.geralt.im.protocol.Request;
import com.geralt.im.protocol.Response;
import com.geralt.im.server.ClientSession;
import com.geralt.im.server.ObjectClientSession;
import com.geralt.im.server.IMServer;
import com.geralt.im.tool.JsonTool;
import com.geralt.im.transmit.ITransmit;

public class Controller {
	
	
	private static Controller controller;
	
	private Controller(){
		
	}
	public static Controller getInstance(){
		if(controller==null){
			controller=new Controller();
		}
		return controller;
	}
	
	public void excute(Request request, ClientSession session) {
		
		Command command = RqParser.getInstance().parse(request);
		command.setSession(session);
		Response response = command.excute();
		System.out.println(request.toString());
		if (response.getStatusCode() == Code.BAD_REQUEST||"REGISTER".equals(request.getType())) {
			session.send(response);
		} else {
			ArrayList<String> receivers = command.getReceivers();
			if (!receivers.isEmpty())
				System.out.println(receivers.get(0));
			// if !null
			for (String id : receivers) {
				if(IMServer.map.get(id)!=null){
					ClientSession session1 = IMServer.map.get(id);
//					String sendString = jt.objectToString(response);
//					session1.send(sendString);
					session1.send(response);
				}
			}
		}
	}
}
